# -*- coding: utf-8 -*-
# Copyright Š 2010 alexliyu
#
# This file is part of cntop-news.
#
# cntop-news is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cntop-news is base on Top-news-buzz ,
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cntop-news.  If not, see <http://www.gnu.org/licenses/>.
import logging

from datetime import datetime, timedelta

from google.appengine.ext import webapp
from google.appengine.ext import db
from topnewsbuzz.utils import DateHelper
from topnewsbuzz.config import Config
from topnewsbuzz.news import NewsManager
from topnewsbuzz.metrics import MetricHelper

class ScoreService(webapp.RequestHandler):

    def get(self):
        score_delay_date =DateHelper().get_nowdate().now() - timedelta(minutes = Config.score_delay_minutes())
        query = db.GqlQuery('SELECT * FROM NewsArticle WHERE publish_date < :score_delay_date AND score = 0.0 AND score_date = NULL', score_delay_date = score_delay_date)
        news_list = query.fetch(Config.articles_to_score_per_pass())

        if len(news_list) == 0:
            logging.debug('Scoring %i articles.' % len(news_list))
        else:
            logging.info('Scoring %i articles.' % len(news_list))

        metrics = MetricHelper.load_metrics()

        for news in news_list:
            news.score = 0.0

            for metric in metrics:
                if metric.enabled:
                    metric_score = metric.apply(news) * metric.boost
                    logging.debug('Score of "%s" for metric "%s": %.2f.' % (news.title, metric.display_name(), metric_score))
                    news.score += metric_score               

            logging.debug('Score of "%s" before applying the score_boost: %.2f.' % (news.title, news.score))
            news.score *= news.score_boost

            if news.score > 0.0:
                NewsManager.invalidate_memcache()
                logging.info('Scoring "%s" with %.2f.' % (news.title, news.score))
            else:
                logging.debug('Article "%s" did not get a score.' % news.title)

            news.score_date =DateHelper.get_nowdate(8).now()
            news.put()


